import axios, { AxiosInstance, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import store from '/@/store'
import router from '/@/router'
const request:AxiosInstance = axios.create({
  // 配置

})
// const noAuthBy401 = () => {
//   if (!store.state.user) {
//     console.log(router)
//     // router.push({
//     //   name: 'login',
//     //   query: {
//     //     redirect: router.currentRoute.pat
//     //   }
//     // })
//   } else {

//   }
// }
// 请求拦截器...todo
request.interceptors.request.use((config) => {
  config.headers.Authorization = store.state.user?.access_token || ''
  return config
}, (error) => {
  return Promise.reject(error)
})
// 响应拦截器...todo
request.interceptors.response.use((response) => {
  return response
}, async (error) => {
  if (error.response) {
    const { status } = error.response
    switch (status) {
      case 400:
        ElMessage.error('请求参数错误')
        break
      case 401:
        window.localStorage.setItem('user', 'null')
        store.commit('setUset', null)
        // console.log(router)
        router.push({
          name: 'login',
          query: {
            redirect: router.currentRoute.value.fullPath
          }
        })
        return Promise.reject(error)
        break
      case 403:
        ElMessage.error('没有权限,请联系管理员！')
        break
      case 404:
        ElMessage.error('请求资源不存在！')
        break
      default:
        ElMessage.error('服务端错误请联系管理员！')
        break
    }
  } else if (error.request) {
    ElMessage.error('请求超时')
  } else {
    ElMessage.error(`请求失败: ${error.message}`)
  }
  return Promise.reject(error)
})

// 类型
export type RequestReturnType = Promise<AxiosResponse>
export default request
